package com.example.tasks

import com.google.gson.GsonBuilder
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.regex.Pattern
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource

/**
 * 用于处理服务器上传图片后返回的XXX.txt的解析，按分组展示
 */

@ExperimentalTime
fun main() {
    val filePath = "F:\\ToolsSources\\pro_content_res.txt"

    pickupWithRegularExpression(filePath)

//    pickGroupedUrls(filePath)

}

/**
 * 更加通用，但首先得保证正则表达式覆盖了所有的url的情况
 */
@ExperimentalTime
 fun pickupWithRegularExpression(filePath: String) {
    val markNow = TimeSource.Monotonic.markNow()
    val regularString = "https*://[A-Za-z0-9_.+/]+\\.(png|webp|jpg)"
    val compile = Pattern.compile(regularString, Pattern.CASE_INSENSITIVE)
    val readText = File(filePath).readText()
    val matcher = compile.matcher(readText)
    val list = ArrayList<String>(100)
    while (matcher.find()) {
        list.add(matcher.group(0))
    }
    val gson = GsonBuilder().setPrettyPrinting().create()

    list/*.sorted()*/.groupBy {
        it.substring(0, it.lastIndexOf("/"))
    }.forEach {
        println("${it.key.substring(1 + it.key.lastIndexOf("/"))}, ${gson.toJson(it.value.sorted())}")
    }
    println("正则匹配耗时：${markNow.elapsedNow()}, 收录${list.size}条数据")
}


/**
 * 根据项目中生成的数据格式特殊处理。准确性较正则更高
 */
@OptIn(ExperimentalTime::class)
private fun pickGroupedUrls(filePath: String) {
    val markNow = TimeSource.Monotonic.markNow()
    val list = ArrayList<String>()

    BufferedReader(InputStreamReader(File(filePath).inputStream())).use {
        do {
            val content = it.readLine()
            if (content.isNotEmpty() && content.isNotBlank()) list.add(content)
        } while (!content.isNullOrEmpty())
    }
    val gson = GsonBuilder().setPrettyPrinting().create()
    var urlCount = 0
    list.asSequence().filter {
        it.isNotEmpty() && it.isNotBlank()
    }.map {
        val index = it.indexOf(",") + 1
        if (index == 0) it.trim() else it.substring(index).trim()
    }.filter {
        it.isNotBlank() && isImage(it)
    }/*.sorted()*/.groupBy {
        it.substring(0, it.lastIndexOf("/"))
    }.forEach {
        println("${it.key.substring(1 + it.key.lastIndexOf("/"))}, ${gson.toJson(it.value.sorted())}")
        urlCount += it.value.size
    }
    println("规则匹配耗时：${markNow.elapsedNow()}, 收录${urlCount}条数据")
}

fun isImage(fileName: String): Boolean {
    val suffix = fileName.substring(1 + fileName.lastIndexOf("."))
    return (suffix.equals("jpg", true)
            || suffix.equals("png", true)
            || suffix.equals("webp", true))
}

